package gae.util.http.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;

public class HttpResponse {
    
    private HttpURLConnection connection = null;
    
    private Header header = null;
    
    private String body = null;
    
    
    
    public void setConnection(HttpURLConnection connection) {
        this.connection = connection;
    }
    
    public HttpURLConnection getConnection() {
        return this.connection;
    }
    
    public Header getHeader() {
        if (header == null) {
            header = new Header();
            header.set(connection.getHeaderFields());
        }
        return header;
    }
    
    public String getBodyToString(String encode) throws IOException {
        if (body != null) {
            return body;
        } else if (connection == null) {
            return null;
        } else {
            StringBuilder sb = new StringBuilder();
            InputStream is = null;
            BufferedReader reader = null;
            try {
                is = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(is, encode));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                    sb.append("\n");
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                throw e;
            } finally {
                try {
                    is.close();
                    reader.close();
                    connection.disconnect();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    throw e;
                }
            }
            return sb.toString();
        }
    }
    
    public int getStatus() throws IOException {
        return this.connection.getResponseCode();
    }
    
}
